#!/bin/bash
# Bootstraps runit config
set -euo pipefail

# Include defaults
. /usr/local/etc/fixinventory/defaults
. /usr/local/etc/fixinventory/common
. /usr/local/fix-venv-python3/bin/activate


main() {
    apply_permissions
    configure_timezone
    setup_etc_hosts || true
    setup_dnsmasq
    exec runuser -u fixinventory -g fixinventory -- "$@"
}


# Apply user id and group id
apply_permissions() {
    info "Setting uid:gid of fixinventory to $PUID:$PGID"
    groupmod -g "${PGID}" -o fixinventory
    #usermod -u "${PUID}" -o -g fixinventory fixinventory
    sed -i -E "s/^(fixinventory:x):[0-9]+:[0-9]+:(.*)/\\1:$PUID:$PGID:\\2/" /etc/passwd

    chown fixinventory:fixinventory /home/fixinventory
    chown -R fixinventory:fixinventory /var/run/fixinventory
}


# Configure timezone
configure_timezone() {
    export TZ
    if [ ! -f "/usr/share/zoneinfo/$TZ" ]; then
        warn "Unknown timezone $TZ - defaulting to Etc/UTC"
        TZ="Etc/UTC"
    fi
    ln -snf "/usr/share/zoneinfo/$TZ" /etc/localtime
    echo "$TZ" > /etc/timezone
    info "Setting timezone $TZ"
}


# Enable/disable IP protocols in /etc/hosts
setup_etc_hosts() {
    local temp_hosts
    temp_hosts="$(mktemp)"
    cat /etc/hosts > "$temp_hosts"

    if ipv4_enabled; then
        sed -i -E "s/^#(127\.0\.0\.1.*)/\1/" "$temp_hosts"
    else
        sed -i -E "s/^(127\.0\.0\.1.*)/#\1/" "$temp_hosts"
    fi

    if ipv6_enabled; then
        sed -i -E "s/^#(::1.*)/\1/" "$temp_hosts"
    else
        sed -i -E "s/^(::1.*)/#\1/" "$temp_hosts"
    fi

    # /etc/hosts is singularly mounted into the container.
    # sed -i is not really working in-place but instead
    # creates a temp file and then moves it. So would fail
    # on /etc/hosts. Instead of atomically moving
    # we cat the temp file into the destination.
    cat "$temp_hosts" > /etc/hosts
    rm -f "$temp_hosts"
}


# Setup dnsmasq DNS caching daemon
setup_dnsmasq() {
    if [ "${USE_DNS_CACHE-}" = true ]; then
        cp /etc/resolv.conf /etc/resolv.dnsmasq
        if [ "${LOG_DNS_QUERIES-}" = true ]; then
            echo "log-queries=extra" >> /etc/dnsmasq.d/fixinventory.conf
        fi
        dnsmasq
        echo "nameserver 127.0.0.1" > /etc/resolv.conf
    fi
}


main "$@"
